package com.example.controller;

import com.example.dao.LikeDiscussDao;
import com.example.model.pojo.LikeDiscussion;
import com.example.model.pojo.Result;
import com.example.model.pojo.UserInfo;
import com.example.untils.RedisUntil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("like")
public class LikeDiscussionController {
    @Autowired
    private LikeDiscussDao likeDiscussDao;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("save")
    public Result  saveLike(Integer discussid, HttpServletRequest request){
        UserInfo userInfo= (UserInfo) request.getAttribute("userInfo");
        String rediskey=RedisUntil.getLikeKey(userInfo.getUuid(),discussid);
        String likeStatus= (String) redisTemplate.opsForValue().get(rediskey);
        if(null!=likeStatus && likeStatus.equals("1"))
        {
            return new Result("400","您已经点过赞了...");
        }
        LikeDiscussion likeDiscussion=new LikeDiscussion();
        likeDiscussion.setUuid(userInfo.getUuid());
        likeDiscussion.setCreateDate(new Date());
        likeDiscussion.setDiscussId(discussid);
        likeDiscussDao.save(likeDiscussion);
        redisTemplate.opsForValue().set(rediskey,"1",1, TimeUnit.DAYS);
        return  new Result("200","success");
    }

    @GetMapping("get")
    public Result  getLikestatus(Integer discussId, HttpServletRequest request){
        UserInfo userInfo= (UserInfo) request.getAttribute("userInfo");
        Integer uuid=userInfo.getUuid();
        Integer likes= likeDiscussDao.getlikes(uuid,discussId);
        if(likes<=0)
        {
            return new Result("400","error");
        }
        return  new Result("200","success",uuid);
    }
}
